package com.example.module_motocircle.post

import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import com.example.demo.adapter.DemoPostListAdapter
import com.example.lib_common.Router
import com.example.lib_common.base.BaseFragment
import com.example.lib_common.base.state.Empty
import com.example.lib_common.base.state.Failed
import com.example.lib_common.base.state.IRetryClickListener
import com.example.lib_common.base.state.Loading
import com.example.lib_common.base.state.Success
import com.example.lib_common.base.state.UILoader
import com.example.lib_common.base.state.UIState
import com.example.lib_common.base.utils.ToastUtils
import com.example.lib_common.observeWithLifecycle
import com.example.lib_common.video.VideoRecyclerViewHelper
import com.example.lib_storage.AuthMMKV
import com.example.module_motocircle.R
import com.example.module_motocircle.adpater.PostListAdapter
import com.example.module_motocircle.adpater.PostViewHolder
import com.example.module_motocircle.databinding.FragmentPostListBinding
import com.example.module_motocircle.databinding.LayoutPostItemBinding
import com.example.module_motocircle.databinding.LayoutRefreshRecyclerviewBinding
import com.example.module_motocircle.helper.LikeGifAnimHelper
import com.example.module_motocircle.model.PostItem
import com.example.module_motocircle.motocircle.MotocircleViewModel
import com.google.android.exoplayer2.util.MimeTypes
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Job

@AndroidEntryPoint
class PostListFragment : BaseFragment<MotocircleViewModel , FragmentPostListBinding>(){
    override val mLayoutResId: Int
        get() = R.layout.fragment_post_list
    private val mViewModel:MotocircleViewModel by viewModels()
    private lateinit var mUiLoader: UILoader
    private lateinit var mContentBinding: LayoutRefreshRecyclerviewBinding
    private var showAuthorLabel: Boolean = true
    private var mPagingJob: Job? = null
    //点赞gif动画
    val helper by lazy {
        LikeGifAnimHelper(requireActivity())
    }
    //视频播放类
    private val mVideoRecyclerViewHelper by lazy {
        object : VideoRecyclerViewHelper(){
            override fun getVideoUrl(position: Int): String? {
                return mPostListAdapter.getPostItem(position)?.image?.firstOrNull()?.url
            }

            override fun isVideo(position: Int): Boolean {
                return MimeTypes.isVideo(mPostListAdapter.getPostItem(position)?.image?.firstOrNull()?.contentType)
            }
            override fun getVideoContainer(viewHolder: RecyclerView.ViewHolder): FrameLayout? {
                if (viewHolder !is PostViewHolder){
                    return null
                }
                val binding = DataBindingUtil.getBinding<LayoutPostItemBinding>(viewHolder.itemView)
                return binding?.lVideo
            }

            override fun getVideoCoverView(viewHolder: RecyclerView.ViewHolder): ImageView? {
                if (viewHolder !is PostViewHolder){
                    return null
                }
                val binding = DataBindingUtil.getBinding<LayoutPostItemBinding>(viewHolder.itemView)
                return binding?.ivVideo
            }

            override fun getVideoIcon(viewHolder: RecyclerView.ViewHolder): View? {
                if (viewHolder !is PostViewHolder){
                    return null
                }
                val binding = DataBindingUtil.getBinding<LayoutPostItemBinding>(viewHolder.itemView)
                return binding?.ivPlay
            }

            override fun getVideoLoadingView(viewHolder: RecyclerView.ViewHolder): View? {
                if (viewHolder !is PostViewHolder){
                    return null
                }
                val binding = DataBindingUtil.getBinding<LayoutPostItemBinding>(viewHolder.itemView)
                return binding?.loading
            }

        }
    }
    //分页参数
    private var ifFocus: Int? = null
    private var keyword: String? = null
    private var memberId: String? = null
    private var topicId: String? = null
    private var sortBy: String? = null
    companion object {
        private const val KEYWORD = "keyword"
        private const val SORT_BY = "sortType"
        private const val MEMBER_ID = "memberId"
        private const val IF_FOCUS = "isFocus"
        private const val TOPIC_ID = "topicId"
        fun newInstance(
            ifFocus: Int? = null,
            keyword: String? = null,
            memberId: String? = null,
            topicId: String? = null,
            sortType: String? = null
        ): PostListFragment {
            val postListFragment = PostListFragment()
            postListFragment.arguments = Bundle().apply {
                putInt(IF_FOCUS, ifFocus ?: 0)
                putString(KEYWORD, keyword)
                putString(MEMBER_ID, memberId)
                putString(TOPIC_ID, topicId)
                putString(SORT_BY, sortType)
            }
            return postListFragment
        }
    }
    private val mPostListAdapter by lazy {
        DemoPostListAdapter(
            onLikeClick = {postItem, i ->

            },
            onLikeViewClick = {postItem, i, view ->
                if(!AuthMMKV.hasLogin()){
                    return@DemoPostListAdapter
                }
//                //优化：开启gif动画
                if (postItem.if_like == 0) {
                    helper.setTargetView(view)
                    helper.startGif()
                }
//                //优化：本地先更新UI，再发起网络请求，若失败回滚UI状态
//                updateLike(postItem)
//                //点赞
                mViewModel.giveLike(postItem.posts_id,i)

            },
            onCommentsClick = {

            },
            onShareClick = {

            },
            onFollowViewClick = {postItem, i, view ->

            },
            onCollectionViewClick = {postItem, i, view ->

            },
            onMoreActionClick = {postItem, i ->

            },
            onItemClick = {postItem, i ->
                ARouter.getInstance().build(Router.Ui.MotocircleDetailActivity).navigation()
            },
            onUserClick =  {postItem ->

            },
            showRelationState = ifFocus == 0 , //是否显示关系
        )
    }

    override fun initView() {
        ifFocus = arguments?.getInt(IF_FOCUS)
        keyword = arguments?.getString(KEYWORD)
        memberId = arguments?.getString(MEMBER_ID)
        topicId = arguments?.getString(TOPIC_ID)
        sortBy = arguments?.getString(SORT_BY)
        initUILoader()
        initAdapter()
    }
    /**
     * 初始化适配器
     */
    private fun initAdapter() {
        mContentBinding.rv.adapter = mPostListAdapter
        mContentBinding.rv.layoutManager = LinearLayoutManager(requireContext())
        mContentBinding.rv.setHasFixedSize(true)
        mContentBinding.rv.setItemViewCacheSize(10)
        val pool = RecyclerView.RecycledViewPool()
        pool.setMaxRecycledViews(0,10)
        mContentBinding.rv.setRecycledViewPool(pool)
        //视频帮助类
        mVideoRecyclerViewHelper.init(
            requireActivity(),mContentBinding.rv,
            onPlayingVideoClick = null,
            onNotPlayingVideoClick = null
        )
        mContentBinding.rv.setOnScrollChangeListener { _, _, _, _, _ ->
            val position =
                (mContentBinding.rv.layoutManager as LinearLayoutManager).findFirstVisibleItemPosition()
            if (position < 3) {
                mContentBinding.ivGoToTop.visibility = View.GONE
            } else {
                mContentBinding.ivGoToTop.visibility = View.VISIBLE
            }
        }

        mContentBinding.ivGoToTop.setOnClickListener {
            mContentBinding.rv.smoothScrollToPosition(0)
        }
    }

    /**
     * 停止播放
     */
    override fun onPause() {
        super.onPause()
        mVideoRecyclerViewHelper.pausePlayer()
    }

    /**
     * 恢复播放
     */
    override fun onResume() {
        super.onResume()
        if (isVisible){
            mVideoRecyclerViewHelper.startPlayer()
        }else{
            mVideoRecyclerViewHelper.hidePlayerView()
        }
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden){
            mVideoRecyclerViewHelper.startPlayer()
        }else{
            mVideoRecyclerViewHelper.pausePlayer()
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        mVideoRecyclerViewHelper.releasePlayer()
    }


    override fun initData() {
        //是否为关注页面
        if (ifFocus == 1){
            if (!AuthMMKV.hasLogin()){//未登录
                mUiLoader.updateState(UIState.UN_LOGIN)
            }else{//已登录 是否有关注人
                mViewModel.checkIfHasFocus()
            }
        }else{
            //直接加载帖子数据
            getPostListData()
        }
    }

    override fun initListener() {
        //判断是否有关注的人
        mViewModel.mCheckIfHasFocus.observe(this){
            if (it){
                //直接加载帖子数据
                getPostListData()
            }else{
                mUiLoader.updateState(UIState.NO_FOLLOW)
            }
        }
        //点赞结果
//        mViewModel._requestLikeEvent.observeWithLifecycle(this){
//            //点赞成功 不做处理
//            //点赞成功 换回来
//            if (it == -1){
//                mPostListAdapter.getItemByPosition(it)?.let {
//                    updateLike(it)
//                }
//            }
//        }
    }
//    private fun updateLike(postItem: PostItem){
//        if (postItem.if_like == 0){
//           postItem.if_like = 1
//           postItem.like_number++
//        }else{
//            postItem.if_like = 0
//            postItem.like_number--
//        }
//        mPostListAdapter.updatePostItem(postItem)
//    }
    /**
     * 初始化全局状态
     */
    private fun initUILoader() {
        mContentBinding = DataBindingUtil.inflate(
            LayoutInflater.from(context),
            R.layout.layout_refresh_recyclerview,
            null,
            false
        )
        mUiLoader = object : UILoader(requireContext()) {
            override fun loadSuccessView(container: ViewGroup?): View {
                return mContentBinding.root
            }
        }.apply { updateState(UIState.LOADING) }

        mUiLoader.onLoginClick = {
//            ARouterUtils.jumpLogin(requireActivity() as? AppCompatActivity)
        }
        mUiLoader.setOnRetryClickListener(object : IRetryClickListener {
            override fun onRetryClick() {

            }
        })
        mBinding.layoutContent.addView(mUiLoader)

    }
    //设置帖子分页参数
    fun setPagingParam(
        sortType: String?,
        keyword: String?,
        memberId: String?,
        ifFocus: Int?,
        topicId: String?
    ) {
        if (mPagingJob?.isActive == true) {
            mPagingJob!!.cancel()
        }
        this.sortBy = sortType
        this.keyword = keyword
        this.memberId = memberId
        this.ifFocus = ifFocus
        this.topicId = topicId
    }
    fun getPostListData(){
        //设置参数
        mViewModel.setPageParam(sortBy,topicId,memberId,ifFocus,topicId)
        //网络请求
//        mViewModel.pageList()
        //订阅帖子数据,防止每次直接订阅显示加载中
//        observePostData()
        mPagingJob = mViewModel.postPageEvent2.observeWithLifecycle(this) {
            mPostListAdapter.submitData(it)
        }
    }
    fun observePostData(){
        mViewModel.mPostState.observeWithLifecycle(this){
            when(it){
                is Loading -> {
                    mUiLoader.updateState(UIState.LOADING)
                }
                is Success -> {
                    mUiLoader.updateState(UIState.SUCCESS)
                    //添加数据源更新UI
//                    mPostListAdapter.setData(mViewModel.mPostListData)
                }
                is Failed -> {
                    mUiLoader.updateState(UIState.NETWORK_ERROR)
                    ToastUtils.showShort(requireActivity(),it.message)
                }
                is Empty -> {
                    mUiLoader.updateState(UIState.EMPTY)
                }
            }
        }
    }
}